/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.ulss.monitor.mainserver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
 *
 * @author YY
 */
public class LoadrateHandler extends AbstractHandler {

    private static LoadrateHandler infoPubHandler = null;
    static Logger logger = Logger.getLogger(ServerStartup.class.getName());

    private LoadrateHandler() {
    }

    public static LoadrateHandler getInfoPubHandler() {
        if (infoPubHandler == null) {
            infoPubHandler = new LoadrateHandler();
        }
        return infoPubHandler;
    }

    /**
     *
     * @param string
     * @param baseRequest
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     * @throws ServletException
     */
    //http://192.168.10.185:8021/loadrate/json/
    @Override
    public void handle(String string, Request baseRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        baseRequest.setHandled(true);
        String remoteHost = baseRequest.getRemoteAddr();
        int remotePort = baseRequest.getRemotePort();
        String reqID = String.valueOf(System.nanoTime());
        logger.info("receive request from " + remoteHost + ":" + remotePort + " and assigned id " + reqID);
        String rate = null;
        String finalrate = null;
        try {
            FileReader reader = new FileReader("sysspeed");
            BufferedReader bufedreader = new BufferedReader(reader);
//            rate = bufedreader.readLine();
            while ((rate = bufedreader.readLine()) != null) {
                finalrate = rate;
            }
        } catch (Exception ex) {
            rate = null;
            logger.error(ex, ex);
        }
        Map<String, String> map = new HashMap<String, String>();
        if (finalrate == null) {
            map.put("result", "fail");
            map.put("loadrate", finalrate);
        } else {
            map.put("result", "success");
            map.put("loadrate", finalrate);
        }

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getWriter().println(map);
    }
}